package org.budo.mongo.jdbc.driver.statement.impl;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.budo.jdbc.driver.AbstractBudoJdbcPreparedStatement;
import org.budo.jdbc.driver.resultset.impl.MapArrayResultSet;
import org.budo.mongo.jdbc.driver.BudoMongoJdbcConnection;
import org.budo.mongo.jdbc.driver.BudoMongoJdbcPreparedStatement;
import org.budo.mongo.jdbc.driver.statement.AbstractMongoStatement;
import org.budo.support.lang.util.MapUtil;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoIterable;

/**
 * @author lmw
 */
public class SHOW_DATABASES extends AbstractMongoStatement {
    @Override
    public void execute(PreparedStatement preparedStatement) throws SQLException{
        try {
            BudoMongoJdbcPreparedStatement mongoPreparedStatement = (BudoMongoJdbcPreparedStatement) preparedStatement;
            BudoMongoJdbcConnection mongoConnection = (BudoMongoJdbcConnection) mongoPreparedStatement.getConnection();
            MongoClient mongoClient = mongoConnection.mongoClient();

            List<Map> maps = new ArrayList<Map>();
            MongoIterable<String> databaseNames = mongoClient.listDatabaseNames();
            MongoCursor<String> databaseNamesCursor = databaseNames.iterator();
            while (databaseNamesCursor.hasNext()) {
                String databaseName = databaseNamesCursor.next();
                maps.add(MapUtil.stringObjectMap("DataBase", databaseName));
            }

            String[] columnNames = new String[] { "DataBase" };
            ResultSet resultSet = new MapArrayResultSet(columnNames, maps.toArray(new Map[maps.size()]));
            ((AbstractBudoJdbcPreparedStatement) preparedStatement).resultSet(resultSet);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}